/**
 * Created by Administrator on 2017/8/22.
 */
var Goods = require('../models/goods');
var User = require('../models/user');

exports.goods = function *(req, res) {
  var page = req.query.page - 0;
  var pageSize = req.query.pageSize - 0;
  var sort = req.query.sort - 0;
  var priceFilter = req.query.priceFilter;
  var skip = (page - 1) * pageSize;
  var params = {};
  if (priceFilter) {
    priceFilter = JSON.parse(req.query.priceFilter);
    params.salePrice = {
      $gte: priceFilter.startPrice,
      $lte: priceFilter.endPrice
    }
  }

  try {
    var _goodsList = yield Goods.find(params).skip(skip).limit(pageSize).sort({'salePrice': sort});
    res.json({
      status: 0,
      msg: '',
      result: {
        count: _goodsList.length,
        list: _goodsList
      }
    });
  } catch (err) {
    res.json({
      status: 1,
      msg: err.message
    });
  }
}

exports.addCart = function *(req, res) {
  var userId = '100000077';
  var goods = req.body;

  //从数据库中找到用户
  try {
    var _user = yield User.findById(userId);
    //判断该用户的cartList中是否已经有该商品了
    var have = false;
    _user.cartList.forEach(function (value) {
      if (value.productId == goods.productId) {
        have = true;
      }
    });

    if (have) { //有该商品进行++
      _user.cartList.forEach(function (value) {
        if (value.productId == goods.productId) {
          value.productNum++;
        }
      });
    } else {  //没有该商品，直接将该商品加入到用户的cartList中
      goods.productNum = 1;
      goods.checked = false;
      _user.cartList.push(goods);
    }
    _user.save();

    res.json({
      status: 0,
      msg: ''
    });

  } catch (err) {
    res.json({
      status: 1,
      msg: err.message
    });
  }
}
